package com.ruoyi.base.resolver;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.base.annotaion.RequestBodyParam;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Objects;

/**
 * 用来读取body中的参数
 *
 * @author lcf
 */
public class RequestBodyParamHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(@NotNull MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestBodyParam.class);
    }

    @Override
    public Object resolveArgument(@NotNull MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  @NotNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        RequestBodyParam requestBodyParam = parameter.getParameterAnnotation(RequestBodyParam.class);
        if (requestBodyParam == null) {
            return null;
        }

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) {
            return null;
        }

        //若没有填写参数名称则与形参一致
        String paramName = Objects.equals(requestBodyParam.value(), "") ?
                parameter.getParameterName() : requestBodyParam.value();

        BufferedReader reader = request.getReader();
        StringBuilder stringBuilder = new StringBuilder();
        char[] buf = new char[1024];
        int rd;
        while ((rd = reader.read(buf)) != -1) {
            stringBuilder.append(buf, 0, rd);
        }

        JSONObject json = JSONObject.parseObject(stringBuilder.toString());

        return json.getObject(paramName, parameter.getParameterType());
    }
}
